#!/bin/bash

# 定义Tomcat和Exam的路径
TOMCAT_PATH="/home/linux_7220765208/Tomcat9/apache-tomcat-9.0.97"
EXAM_PATH="/home/linux_7220765208/Exam"
TARGET_DIR="${EXAM_PATH}/target"

# 步骤1：准备CP变量
CP=""
# 将Tomcat下的lib目录下的所有jar包文件名取出并添加到变量CP中
for jar in "${TOMCAT_PATH}/lib/servlet-api.jar" "${TOMCAT_PATH}/webapps/ROOT/WEB-INF/lib/"*.jar; do
    CP+="$(readlink -f "$jar"):"
done

# 去掉末尾的冒号
CP=${CP%:}

echo "Classpath: $CP"

# 确保target目录存在
mkdir -p "$TARGET_DIR"

# 步骤2：编译
# javac编译所有java文件，并将生成的class文件放入target目录中
javac -cp "$CP" -d "$TARGET_DIR" "${EXAM_PATH}/code/"*.java

# 判断编译是否成功
if [ $? -ne 0 ]; then
    echo "Compilation failed, exiting."
    exit 1
else
    echo "Compilation successful."
fi

# 步骤3：部署
# 将target目录下的所有class文件复制到Tomcat的WEB-INF/classes目录中，覆盖原文件
cp -rf "$TARGET_DIR"/* "${TOMCAT_PATH}/webapps/ROOT/WEB-INF/classes/"

echo "Deployment successful."

# 步骤4：重启
# 重启tomcat
echo "Restarting Tomcat..."
sh "${TOMCAT_PATH}/bin/shutdown.sh"
sleep 5
sh "${TOMCAT_PATH}/bin/startup.sh"

echo "Tomcat restarted."
